<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item v-if="formData.type == 1" label="袋型" prop="bagType">
          <VtRadioGroup
            v-model="formData.bagType"
            type="bagType"
            :filter-type="1"
            :multiple="false"
            start
            @change="handleBagTypeChange"
          />
        </el-form-item>
        <el-form-item v-else label="袋型" prop="bagType">
          <VtRadioGroup
            v-model="formData.bagType"
            type="bagType"
            :filter-type="2"
            :multiple="false"
            start
            @change="handleBagTypeChange"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider v-if="!isRollFilm" content-position="left">尺寸信息</el-divider>
    <el-row v-if="!isRollFilm" :gutter="20">
      <el-col :span="6">
        <el-form-item label="尺寸" prop="selectedSize">
          <VtSelect
            v-model="formData.selectedSize"
            type="size"
            placeholder="快速选择可修改"
            @change="handleSizeChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="宽度(mm)" prop="l">
          <el-input-number
            v-model="formData.l"
            :min="0"
            placeholder="宽度(mm)"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="高度(mm)" prop="w">
          <el-input-number
            v-model="formData.w"
            :min="0"
            placeholder="高度(mm)"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="全展(mm)" prop="h">
          <el-input-number
            v-model="formData.h"
            :min="0"
            placeholder="全展(mm)"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="单面厚度(丝)" prop="thickness" label-width="100px">
          <el-input-number
            v-model="formData.thickness"
            :min="0"
            placeholder=""
            style="width: 200px"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="其他规格" prop="remark2">
          <el-input
            v-model="formData.remark2"
            style="width: 100%"
            maxlength="2000"
            show-word-limit
            rows="4"
            type="textarea"
            placeholder="添加其他规格信息或者任意备注"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider content-position="left">工艺信息</el-divider>
    <!-- 卷膜工艺信息 -->
    <el-row v-if="isRollFilm" :gutter="20">
      <el-col :span="12">
        <el-form-item label="材质" prop="rollMaterial">
          <el-select
            v-model="formData.rollMaterial"
            placeholder="请选择材质"
            style="width: 100%"
            @change="handleRollMaterialChange"
          >
            <el-option
              v-for="material in rollMaterialOptions"
              :key="material"
              :label="material"
              :value="material"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="复合工艺" prop="rollCompositeType">
          <el-checkbox-group
            v-model="formData.rollCompositeType"
            @change="handleRollCompositeTypeChange"
          >
            <el-checkbox
              v-for="option in rollCompositeOptions"
              :key="option.value"
              :label="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 非卷膜工艺信息 -->
    <el-row v-if="!isRollFilm" :gutter="20">
      <el-col v-show="formData.type == 0" :span="24">
        <el-form-item label="制袋工艺" prop="bagProcess">
          <VtRadioGroup
            v-model="formData.bagProcess"
            type="bagType"
            start
            :filter-type="0"
            :multiple="false"
            @change="handleBagProcessChange"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row v-if="!isRollFilm" :gutter="20">
      <el-col :span="12">
        <el-form-item label="材质" prop="material">
          <VtRadioGroup
            v-model="formData.material"
            type="material"
            @change="handleMaterialChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="复合工艺" prop="compositeType">
          <VtRadioGroup
            v-model="formData.compositeType"
            type="compositeType"
            @change="handleCompositeTypeChange"
          />
        </el-form-item>
        <el-form-item label="印刷颜色" prop="surfaceFee">
          <VtRadioGroup
            v-model="formData.surfaceFee"
            type="surfaceFee"
            @change="handleSurfaceFeeChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="配件" prop="accessory">
          <AccessorySelect
            v-model="formData.accessory"
            :width="formData.l || 0"
            :height="formData.w || 0"
            @change="handleAccessoryChange"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider content-position="left">{{ isRollFilm ? "重量信息" : "数量信息" }}</el-divider>
    <!-- 卷膜模式：显示重量输入 -->
    <el-row v-if="isRollFilm" :gutter="20">
      <el-col :span="8">
        <el-form-item label="重量(kg)" prop="weight1">
          <RollWeightInput v-model="formData.weight1" placeholder="重量(kg)" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量2(kg)" prop="weight2">
          <RollWeightInput v-model="formData.weight2" placeholder="重量2(kg)" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量3(kg)" prop="weight3">
          <RollWeightInput v-model="formData.weight3" placeholder="重量3(kg)" />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 非卷膜模式：显示数量输入 -->
    <el-row v-else :gutter="20">
      <el-col :span="8">
        <el-form-item label="数量(个)" prop="quantity1">
          <QuantityInput v-model="formData.quantity1" placeholder="数量" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="数量2" prop="quantity2">
          <QuantityInput v-model="formData.quantity2" placeholder="数量2" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="数量3" prop="quantity3">
          <QuantityInput v-model="formData.quantity3" placeholder="数量3" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider content-position="left">价格信息</el-divider>
    <!-- 卷膜显示价格计算 -->
    <el-row v-if="isRollFilm" :gutter="20">
      <el-col :span="8">
        <el-form-item label-width="0px" prop="roll_price1">
          <PriceDisplay
            :price-data="rollPrice1"
            :quantity="formData.weight1"
            :show-details="true"
            :is-roll-film="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label-width="0px" prop="roll_price2">
          <PriceDisplay
            :price-data="rollPrice2"
            :quantity="formData.weight2"
            :show-details="true"
            :is-roll-film="true"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label-width="0px" prop="roll_price3">
          <PriceDisplay
            :price-data="rollPrice3"
            :quantity="formData.weight3"
            :show-details="true"
            :is-roll-film="true"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 机印工艺显示计算价格 -->
    <el-row v-else-if="formData.type == 0 || formData.type == 2" :gutter="20">
      <el-col :span="8">
        <el-form-item label-width="0px" prop="cal_price1">
          <PriceDisplay
            :price-data="systemPrice1"
            :quantity="formData.quantity1"
            :show-details="true"
          />
          <el-form-item
            v-hasPerm="['vt:vt-order-form:price-detail']"
            label-width="50px"
            label="损耗"
            prop="priceRatio1"
            style="margin-top: 10px"
          >
            <el-input-number
              v-model="formData.priceRatio1"
              :min="0"
              placeholder="损耗"
              style="width: 100%"
            />
          </el-form-item>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label-width="0px" prop="cal_price2">
          <PriceDisplay
            :price-data="systemPrice2"
            :quantity="formData.quantity2"
            :show-details="true"
          />
          <el-form-item
            v-hasPerm="['vt:vt-order-form:price-detail']"
            label-width="50px"
            label="损耗"
            prop="priceRatio2"
            style="margin-top: 10px"
          >
            <el-input-number
              v-model="formData.priceRatio2"
              :min="0"
              placeholder="损耗"
              style="width: 100%"
            />
          </el-form-item>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label-width="0px" prop="cal_price3">
          <PriceDisplay
            :price-data="systemPrice3"
            :quantity="formData.quantity3"
            :show-details="true"
          />
          <el-form-item
            v-hasPerm="['vt:vt-order-form:price-detail']"
            label-width="50px"
            label="损耗"
            prop="priceRatio3"
            style="margin-top: 10px"
          >
            <el-input-number
              v-model="formData.priceRatio3"
              :min="0"
              placeholder="损耗"
              style="width: 100%"
            />
          </el-form-item>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 订单信息：新增模式不显示重量和总价 -->
    <el-divider v-if="!isAddMode" content-position="left">订单信息</el-divider>
    <!-- 报价员模式在status=0,1时可以修改重量 -->
    <el-row
      v-if="
        !isAddMode &&
        isQuoteMode &&
        (formData.status === 0 || formData.status === 1 || formData.status === 3)
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="重量(kg)" prop="weight1">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.weight1"
              :min="0"
              placeholder="重量"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(1)"
              @click="handleImportWeight(1)"
            >
              带入
            </el-button>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量2" prop="weight2">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.weight2"
              :min="0"
              placeholder="重量2"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(2)"
              @click="handleImportWeight(2)"
            >
              带入
            </el-button>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量3" prop="weight3">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.weight3"
              :min="0"
              placeholder="重量3"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(3)"
              @click="handleImportWeight(3)"
            >
              带入
            </el-button>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 其他模式显示重量但不可编辑 -->
    <el-row
      v-if="
        !isAddMode &&
        (!isQuoteMode || (formData.status !== 0 && formData.status !== 1 && formData.status !== 3))
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="重量(kg)" prop="weight1">
          <el-input-number
            v-model="formData.weight1"
            :min="0"
            placeholder="重量"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量2" prop="weight2">
          <el-input-number
            v-model="formData.weight2"
            :min="0"
            placeholder="重量2"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量3" prop="weight3">
          <el-input-number
            v-model="formData.weight3"
            :min="0"
            placeholder="重量3"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 报价员模式在status=0,1时可以修改总价 -->
    <el-row
      v-if="
        !isAddMode &&
        isQuoteMode &&
        (formData.status === 0 || formData.status === 1 || formData.status === 3)
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="总价(元)" prop="price1">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.price1"
              :min="0"
              placeholder="总价"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(1)"
              @click="handleImportPrice(1)"
            >
              带入
            </el-button>
          </div>
          <div v-if="unitPrice1 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice1.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价2" prop="price2">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.price2"
              :min="0"
              placeholder="总价2"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(2)"
              @click="handleImportPrice(2)"
            >
              带入
            </el-button>
          </div>
          <div v-if="unitPrice2 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice2.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价3" prop="price3">
          <div class="input-with-button">
            <el-input-number
              v-model="formData.price3"
              :min="0"
              placeholder="总价3"
              style="width: 100%"
            />
            <el-button
              type="primary"
              size="small"
              :disabled="!hasCalculatedData(3)"
              @click="handleImportPrice(3)"
            >
              带入
            </el-button>
          </div>
          <div v-if="unitPrice3 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice3.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="版费" prop="plateFee">
          <el-input-number
            v-model="formData.plateFee"
            :min="0"
            placeholder="版费"
            style="width: 500px"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 其他模式显示总价但不可编辑 -->
    <el-row
      v-if="
        !isAddMode &&
        (!isQuoteMode || (formData.status !== 0 && formData.status !== 1 && formData.status !== 3))
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="总价(元)" prop="price1">
          <el-input-number
            v-model="formData.price1"
            :min="0"
            placeholder="总价"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice1 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice1.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价2" prop="price2">
          <el-input-number
            v-model="formData.price2"
            :min="0"
            placeholder="总价2"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice2 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice2.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价3" prop="price3">
          <el-input-number
            v-model="formData.price3"
            :min="0"
            placeholder="总价3"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice3 > 0 && !isRollFilm" class="unit-price-display">
            单价：{{ unitPrice3.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="版费" prop="plateFee">
          <el-input-number
            v-model="formData.plateFee"
            :min="0"
            disabled
            placeholder="版费"
            style="width: 500px"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { computed, ref, watch, nextTick } from "vue";
import { useConfigStore } from "@/store/modules/config.store.js";
import { useVtOptionsStore } from "@/store/modules/vt-options.store.js";
import { usePriceCalculator } from "@/composables/usePriceCalculator.js";
import { ElMessage } from "element-plus";

defineOptions({
  name: "MechanicalPrint",
  inheritAttrs: false,
});

const props = defineProps({
  formData: {
    type: Object,
    required: true,
  },
  isAddMode: {
    type: Boolean,
    default: false,
  },
  isQuoteMode: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:formData"]);

const configStore = useConfigStore();
const vtOptionsStore = useVtOptionsStore();

// 加载配置数据
if (!configStore.loaded) {
  configStore.loadConfigs();
}

// 卷膜选项数据
const rollOptions = ref([]);

// 卷膜材质选项（从rollOptions中的name去重）
const rollMaterialOptions = ref([]);

// 卷膜复合工艺选项
const rollCompositeOptions = ref([
  { value: "PET哑油", label: "PET哑油 +1元/kg", price: 1 },
  { value: "冷冻PE", label: "冷冻PE +2元/kg", price: 2 },
  { value: "加强防静电膜", label: "加强防静电膜 +2元/kg", price: 2 },
]);

// 检测是否选择了卷膜
const isRollFilm = computed(() => {
  return props.formData.bagType === "卷膜";
});

/**
 * 根据数量获取价格比例配置
 */
async function getPriceRatioByQuantity(quantity) {
  // 确保价格损耗数据已加载
  if (!configStore.priceLossData) {
    await configStore.loadPriceLossData();
  }
  return configStore.getPriceRatioByQuantity(quantity);
}

// 初始化价格计算器
const { calculateSystemPrice } = usePriceCalculator(props.formData);

// 系统价格计算结果
const systemPrice1 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    area: 0,
    weight: 0,
    material: { price: 0, details: [] },
    bagProcess: { price: 0, details: [] },
    composite: { price: 0, details: [] },
    surface: { price: 0, details: [] },
    accessory: { price: 0, details: [] },
    plateFee: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

const systemPrice2 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    area: 0,
    weight: 0,
    material: { price: 0, details: [] },
    bagProcess: { price: 0, details: [] },
    composite: { price: 0, details: [] },
    surface: { price: 0, details: [] },
    accessory: { price: 0, details: [] },
    plateFee: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

const systemPrice3 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    area: 0,
    weight: 0,
    material: { price: 0, details: [] },
    bagProcess: { price: 0, details: [] },
    composite: { price: 0, details: [] },
    surface: { price: 0, details: [] },
    accessory: { price: 0, details: [] },
    plateFee: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

// 卷膜价格计算结果
const rollPrice1 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    weight: 0,
    rollType: "",
    basePrice: 0,
    rollMaterial: "",
    rollCompositeType: [],
    compositePrice: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

const rollPrice2 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    weight: 0,
    rollType: "",
    basePrice: 0,
    rollMaterial: "",
    rollCompositeType: [],
    compositePrice: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

const rollPrice3 = ref({
  totalPrice: 0,
  unitPrice: 0,
  details: {
    weight: 0,
    rollType: "",
    basePrice: 0,
    rollMaterial: "",
    rollCompositeType: [],
    compositePrice: 0,
    boxFee: 0,
    boxCount: 0,
    boxPrice: 3.5,
  },
});

// 单价计算
const unitPrice1 = computed(() => {
  if (!props.formData.price1 || !props.formData.quantity1 || props.formData.quantity1 <= 0) {
    return 0;
  }
  return props.formData.price1 / props.formData.quantity1;
});

const unitPrice2 = computed(() => {
  if (!props.formData.price2 || !props.formData.quantity2 || props.formData.quantity2 <= 0) {
    return 0;
  }
  return props.formData.price2 / props.formData.quantity2;
});

const unitPrice3 = computed(() => {
  if (!props.formData.price3 || !props.formData.quantity3 || props.formData.quantity3 <= 0) {
    return 0;
  }
  return props.formData.price3 / props.formData.quantity3;
});

/** 根据数量更新价格比例 */
async function updatePriceRatiosByQuantity() {
  if (props.formData.quantity1) {
    const newRatio1 = await getPriceRatioByQuantity(props.formData.quantity1);
    props.formData.priceRatio1 = newRatio1;
  }

  if (props.formData.quantity2) {
    const newRatio2 = await getPriceRatioByQuantity(props.formData.quantity2);
    props.formData.priceRatio2 = newRatio2;
  }

  if (props.formData.quantity3) {
    const newRatio3 = await getPriceRatioByQuantity(props.formData.quantity3);
    props.formData.priceRatio3 = newRatio3;
  }
}

/** 计算卷膜复合工艺价格 */
function calculateRollCompositePrice(weight) {
  if (
    !props.formData.rollCompositeType ||
    props.formData.rollCompositeType.length === 0 ||
    !weight
  ) {
    return 0;
  }

  let totalCompositePrice = 0;
  props.formData.rollCompositeType.forEach((compositeType) => {
    const option = rollCompositeOptions.value.find((opt) => opt.value === compositeType);
    if (option) {
      totalCompositePrice += option.price; // 每kg额外费用
    }
  });

  return totalCompositePrice;
}

/** 计算卷膜价格 */
async function calculateRollPrice(weight, _quoteNumber) {
  if (!weight || weight <= 0) {
    return {
      totalPrice: 0,
      unitPrice: 0,
      details: {
        weight: 0,
        rollType: "",
        basePrice: 0,
        rollMaterial: props.formData.rollMaterial || "",
        rollCompositeType: props.formData.rollCompositeType || [],
        compositePrice: 0,
        boxFee: 0,
        boxCount: 0,
        boxPrice: 3.5,
      },
    };
  }

  try {
    // 根据选择的材质过滤rollOptions
    let filteredOptions = rollOptions.value;
    if (props.formData.rollMaterial) {
      filteredOptions = rollOptions.value.filter(
        (option) => option.value === props.formData.rollMaterial
      );
    }

    if (filteredOptions.length === 0) {
      return {
        totalPrice: 0,
        unitPrice: 0,
        details: {
          weight: 0,
          rollType: "",
          basePrice: 0,
          rollMaterial: props.formData.rollMaterial || "",
          rollCompositeType: props.formData.rollCompositeType || [],
          compositePrice: 0,
          boxFee: 0,
          boxCount: 0,
        },
      };
    }

    const suitableOption = filteredOptions.find((option) => weight <= option.maxNum);

    if (!suitableOption) {
      const lastOption = filteredOptions[filteredOptions.length - 1];
      const basePrice = lastOption ? lastOption.price : 0;

      // 计算复合工艺价格
      const compositePrice = calculateRollCompositePrice(weight);

      // 计算纸箱费用：15kg一个纸箱，每个纸箱价格从配置获取
      const boxCount = Math.ceil(weight / 15);
      const boxPrice = configStore.getBagPrice || 3.5;
      const boxFee = boxCount * boxPrice;

      const unitPrice = basePrice + compositePrice;
      const totalPrice = unitPrice * weight + boxFee;

      return {
        totalPrice: totalPrice,
        unitPrice: unitPrice,
        details: {
          weight: weight,
          rollType: lastOption ? lastOption.value : "",
          basePrice: basePrice,
          rollMaterial: props.formData.rollMaterial || "",
          rollCompositeType: props.formData.rollCompositeType || [],
          compositePrice: compositePrice,
          boxFee: boxFee,
          boxCount: boxCount,
          boxPrice: boxPrice,
        },
      };
    }

    const basePrice = suitableOption.price;

    // 计算复合工艺价格
    const compositePrice = calculateRollCompositePrice(weight);

    // 计算纸箱费用：15kg一个纸箱，每个纸箱价格从配置获取
    const boxCount = Math.ceil(weight / 15);
    const boxPrice = configStore.getBagPrice || 3.5;
    const boxFee = boxCount * boxPrice;

    const unitPrice = basePrice + compositePrice;
    const totalPrice = unitPrice * weight + boxFee;

    return {
      totalPrice: totalPrice,
      unitPrice: unitPrice,
      details: {
        weight: weight,
        rollType: suitableOption.value,
        basePrice: basePrice,
        rollMaterial: props.formData.rollMaterial || "",
        rollCompositeType: props.formData.rollCompositeType || [],
        compositePrice: compositePrice,
        boxFee: boxFee,
        boxCount: boxCount,
        boxPrice: boxPrice,
      },
    };
  } catch (error) {
    console.error("计算卷膜价格失败:", error);
    return {
      totalPrice: 0,
      unitPrice: 0,
      details: {
        weight: 0,
        rollType: "",
        basePrice: 0,
        rollMaterial: "",
        rollCompositeType: [],
        compositePrice: 0,
        boxFee: 0,
        boxCount: 0,
        boxPrice: 3.5,
      },
    };
  }
}

/** 计算卷膜价格（更新对应的价格数据） */
async function calculateRollPrices() {
  if (!isRollFilm.value) return;

  try {
    const [price1, price2, price3] = await Promise.all([
      calculateRollPrice(props.formData.weight1, 1),
      calculateRollPrice(props.formData.weight2, 2),
      calculateRollPrice(props.formData.weight3, 3),
    ]);

    rollPrice1.value = price1;
    rollPrice2.value = price2;
    rollPrice3.value = price3;
  } catch (error) {
    console.error("计算卷膜价格失败:", error);
  }
}

/** 加载卷膜选项数据 */
async function loadRollOptions() {
  try {
    rollOptions.value = await vtOptionsStore.getRollOptions();

    // 从rollOptions中提取材质选项（去重）
    const materialNames = [...new Set(rollOptions.value.map((option) => option.value))];
    rollMaterialOptions.value = materialNames;
  } catch (error) {
    console.error("加载卷膜选项失败:", error);
    rollOptions.value = [];
    rollMaterialOptions.value = [];
  }
}

/** 计算系统价格 */
async function calculatePrices() {
  try {
    if (props.formData.type == 1) {
      return;
    }
    const [price1, price2, price3] = await Promise.all([
      calculateSystemPrice(props.formData.quantity1, props.formData.priceRatio1),
      calculateSystemPrice(props.formData.quantity2, props.formData.priceRatio2),
      calculateSystemPrice(props.formData.quantity3, props.formData.priceRatio3),
    ]);

    systemPrice1.value = price1;
    systemPrice2.value = price2;
    systemPrice3.value = price3;
  } catch (error) {
    console.error("计算价格失败:", error);
  }
}

// VT选择器变化处理函数
function handleBagTypeChange(value, option) {
  console.log("袋型选择:", value, option);
  emit("update:formData", { ...props.formData });
}

function handleBagProcessChange(value, option) {
  console.log("制袋工艺选择:", value, option);
  emit("update:formData", { ...props.formData });
}

function handleMaterialChange(values, options) {
  console.log("材质选择:", values, options);
  emit("update:formData", { ...props.formData });
}

function handleCompositeTypeChange(values, options) {
  console.log("复合工艺选择:", values, options);
  emit("update:formData", { ...props.formData });
}

function handleSurfaceFeeChange(values, options) {
  console.log("印刷颜色选择:", values, options);
  emit("update:formData", { ...props.formData });
}

function handleAccessoryChange(values, options) {
  console.log("配件选择:", values, options);
  emit("update:formData", { ...props.formData });
}

function handleSizeChange(value, option) {
  console.log("尺寸选择:", value, option);
  if (option && option.l && option.w) {
    props.formData.l = option.l;
    props.formData.w = option.w;
    props.formData.h = option.h;
  }
  emit("update:formData", { ...props.formData });
}

function handleRollMaterialChange(value) {
  console.log("卷膜材质选择:", value);
  emit("update:formData", { ...props.formData });
}

function handleRollCompositeTypeChange(values) {
  console.log("卷膜复合工艺选择:", values);
  emit("update:formData", { ...props.formData });
}

// 检查是否有计算数据
const hasCalculatedData = (index) => {
  let data;

  const isRoll = props.formData.bagType === "卷膜";
  switch (index) {
    case 1:
      data = isRoll ? rollPrice1.value : systemPrice1.value;
      break;
    case 2:
      data = isRoll ? rollPrice2.value : systemPrice2.value;
      break;
    case 3:
      data = isRoll ? rollPrice3.value : systemPrice3.value;
      break;
    default:
      return false;
  }
  return (
    data && data.totalPrice && data.details && (data.details.totalWeight || data.details.weight)
  );
};

// 处理带入重量
const handleImportWeight = (index) => {
  try {
    let calculatedData;

    const isRoll = props.formData.bagType === "卷膜";
    switch (index) {
      case 1:
        calculatedData = isRoll ? rollPrice1.value : systemPrice1.value;
        break;
      case 2:
        calculatedData = isRoll ? rollPrice2.value : systemPrice2.value;
        break;
      case 3:
        calculatedData = isRoll ? rollPrice3.value : systemPrice3.value;
        break;
      default:
        return;
    }

    if (calculatedData && (calculatedData.details.totalWeight || calculatedData.details.weight)) {
      const weightField = `weight${index}`;
      props.formData[weightField] =
        calculatedData.details.totalWeight || calculatedData.details.weight;

      ElMessage.success(
        `已带入重量：${calculatedData.details.totalWeight || calculatedData.details.weight}kg`
      );

      // 触发 formData 更新
      emit("update:formData", { ...props.formData });
    } else {
      ElMessage.warning("无法获取计算重量，请检查数据完整性");
    }
  } catch (error) {
    console.error("带入重量失败:", error);
    ElMessage.error("带入重量失败，请重试");
  }
};

// 处理带入价格
const handleImportPrice = (index) => {
  try {
    let calculatedData;

    const isRoll = props.formData.bagType === "卷膜";
    switch (index) {
      case 1:
        calculatedData = isRoll ? rollPrice1.value : systemPrice1.value;
        break;
      case 2:
        calculatedData = isRoll ? rollPrice2.value : systemPrice2.value;
        break;
      case 3:
        calculatedData = isRoll ? rollPrice3.value : systemPrice3.value;
        break;
      default:
        return;
    }

    if (calculatedData && calculatedData.totalPrice) {
      const priceField = `price${index}`;
      props.formData[priceField] = calculatedData.totalPrice;

      ElMessage.success(`已带入价格：¥${calculatedData.totalPrice}`);

      // 触发 formData 更新
      emit("update:formData", { ...props.formData });
    } else {
      ElMessage.warning("无法获取计算价格，请检查数据完整性");
    }
  } catch (error) {
    console.error("带入价格失败:", error);
    ElMessage.error("带入价格失败，请重试");
  }
};

// 监听类型切换，现货数码印时清空重量
watch(
  () => props.formData.type,
  (newType, oldType) => {
    if (newType === 1 && oldType !== undefined) {
      props.formData.weight1 = 0;
      props.formData.weight2 = 0;
      props.formData.weight3 = 0;
    }
  }
);

// 监听袋型切换，处理卷膜字段清空
watch(
  () => props.formData.bagType,
  (newBagType, oldBagType) => {
    if (newBagType !== oldBagType) {
      if (newBagType === "卷膜") {
        // 切换到卷膜时，清空非卷膜字段
        props.formData.material = [];
        props.formData.compositeType = [];
      } else {
        // 切换到非卷膜时，清空卷膜字段
        props.formData.rollMaterial = "";
        props.formData.rollCompositeType = [];
      }
    }
  }
);

// 监听数量变化，自动更新对应的价格比例
watch(
  () => [props.formData.quantity1, props.formData.quantity2, props.formData.quantity3],
  (_newQuantities, _oldQuantities) => {
    clearTimeout(updatePriceRatiosByQuantity.timer);
    updatePriceRatiosByQuantity.timer = setTimeout(async () => {
      await updatePriceRatiosByQuantity();
    }, 100);
  },
  { deep: true }
);

// 监听重量变化，自动计算卷膜价格
watch(
  () => [
    props.formData.weight1,
    props.formData.weight2,
    props.formData.weight3,
    props.formData.rollMaterial,
    props.formData.rollCompositeType,
  ],
  (_newWeights, _oldWeights) => {
    clearTimeout(calculateRollPrices.timer);
    calculateRollPrices.timer = setTimeout(() => {
      calculateRollPrices();
    }, 300);
  },
  { deep: true }
);

// 监听表单数据变化，自动计算价格
watch(
  () => [
    props.formData.type,
    props.formData.bagType,
    props.formData.bagProcess,
    props.formData.material,
    props.formData.compositeType,
    props.formData.rollMaterial,
    props.formData.rollCompositeType,
    props.formData.surfaceFee,
    props.formData.accessory,
    props.formData.l,
    props.formData.w,
    props.formData.h,
    props.formData.quantity1,
    props.formData.quantity2,
    props.formData.quantity3,
    props.formData.plateFee,
    props.formData.priceRatio1,
    props.formData.priceRatio2,
    props.formData.priceRatio3,
  ],
  () => {
    clearTimeout(calculatePrices.timer);
    calculatePrices.timer = setTimeout(() => {
      calculatePrices();
    }, 300);
  },
  { deep: true }
);

// 初始化
loadRollOptions();

// 初始化价格计算
nextTick(() => {
  calculatePrices();
});
</script>

<style scoped>
.unit-price-display {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.input-with-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-with-button .el-input-number {
  flex: 1;
}

.input-with-button .el-button {
  flex-shrink: 0;
  white-space: nowrap;
}
</style>
